Page({
  data: {
    userInfo: {},
    studentId: '',
    userName: '',
    showInviteModal: false,
    inviteCode: '',
    inputStudentId: ''
  },

  onShareAppMessage() {
    return {};
  },

  onShow() {
    this.getUserInfo();
  },

  onLoad() {
    this.getUserInfo();
  },

  getUserInfo() {
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        studentId: userInfo.studentId || '',
        userName: userInfo.user_name || ''
      });
    } else {
      // 如果本地存储没有用户信息，重新获取
      wx.cloud.callFunction({
        name: 'login',
        data: {}
      }).then(res => {
        if (res.result && !res.result.error) {
          const userInfo = {
            userId: res.result.userId,
            studentId: res.result.studentId,
            managerId: res.result.managerId,
            user_name: res.result.userName || ''
          };
          wx.setStorageSync('userInfo', userInfo);
          this.setData({
            userInfo: userInfo,
            studentId: userInfo.studentId || '',
            userName: userInfo.user_name || ''
          });
        }
      }).catch(err => {
        console.error('获取用户信息失败:', err);
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      });
    }
  },

  // 生成6位邀请码（大写字母和数字组合）
  generateInviteCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let code = '';
    for (let i = 0; i < 6; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return code;
  },

  // 处理邀请码点击
  async handleInviteCode() {
    // 如果还没有邀请码，生成一个
    if (!this.data.inviteCode) {
      const code = this.generateInviteCode();
      this.setData({
        inviteCode: code
      });
    }
    // 显示弹窗
    this.setData({
      showInviteModal: true
    });
  },

  // 处理关闭弹窗
  handleCloseModal() {
    this.setData({
      showInviteModal: false
    });
  },

  // 处理提交
  async handleSubmit() {
    if (!this.data.inputStudentId) {
      wx.showToast({
        title: '请输入学号',
        icon: 'none'
      });
      return;
    }

    try {
      // 调用云函数保存邀请码和学号
      const res = await wx.cloud.callFunction({
        name: 'saveManagerInfo',
        data: {
          inviteCode: this.data.inviteCode,
          studentId: this.data.inputStudentId
        }
      });

      if (res.result.error) {
        throw new Error(res.result.error);
      }

      // 更新本地存储
      const userInfo = this.data.userInfo;
      userInfo.studentId = this.data.inputStudentId;
      wx.setStorageSync('userInfo', userInfo);

      // 更新页面显示
      this.setData({
        studentId: this.data.inputStudentId,
        showInviteModal: false
      });

      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });

    } catch (error) {
      console.error('保存失败:', error);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  },

  // 处理导入
  handleImport() {
    wx.navigateTo({
      url: '../import/index'
    });
  },

  // 处理定制
  handleCustomize() {
    wx.navigateTo({
      url: '/pages/user/customize/index'
    });
  },

  // 处理查询
  handleQuery() {
    wx.navigateTo({
      url: '/pages/common/logistics/index'
    });
  },

  // 处理签领
  handleReceipt() {
    wx.navigateTo({
      url: '../confirm-receipt/index'
    });
  },

  // 处理主页点击
  handleHome() {
    wx.reLaunch({
      url: '/pages/manager/home/index'
    });
  },

  // 处理管理页点击
  handleManage() {
    wx.navigateTo({
      url: '/pages/manager/orders/index'
    });
  },

  // 处理个人资料点击
  handleProfile() {
    wx.navigateTo({
      url: '/pages/manager/profile/index'
    });
  }
});